package com.loveyukari.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.PostConstruct;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.loveyukari.dao.VoteDao;
import com.loveyukari.model.Auth;
import com.loveyukari.model.VoteGroup;
import com.loveyukari.model.VoteItem;

/**
*
*yangshaohua
*2017年5月20日下午5:19:15
**/
@Service
public class VoteService {
	
	private Logger log = LoggerFactory.getLogger(VoteService.class);

	private Map<String,Set<Integer>> vote;
	
	private Set<Integer> checkSet;
	
	private boolean voteFlag = false;

	@Autowired
	private VoteDao voteDao;
	
	@Autowired
	private AuthService authService;
	
	@PostConstruct
	public void init(){
		VoteGroup group = voteDao.selectLastVoteGroup();
		if (group != null && group.getEndTime() == null){
			List<VoteItem> list = voteDao.selectVoteItemByGroup(group.getId());
			if (this.vote == null){
				vote = new HashMap<String, Set<Integer>>();
			}
			for (VoteItem voteItem : list) {
				Set<Integer> set = vote.get(voteItem.getKey());
				if (set == null){
					set = new HashSet<Integer>();
					vote.put(voteItem.getKey(), set);
				}
			}
			this.voteFlag = true;
			this.checkSet = new HashSet<Integer>();
		}
	}
	
	
	//开始投票
	public Integer startVote(String name,String[] keys,String[] notes){
		VoteGroup group = voteDao.selectLastVoteGroup();
		if (group != null || keys == null || keys.length == 0){
			return -1;
		}
		this.voteFlag = false;
		Integer groupId = voteDao.insertVoteGroup(name);
		this.vote = new HashMap<String, Set<Integer>>();
		this.checkSet = new HashSet<Integer>();
		for (int i = 0; i < keys.length; i++) {
			String key = keys[i];
			if (StringUtils.isBlank(key)){
				continue;
			}
			String note = "";
			try {
				note = notes[i];
			} catch (Exception e) {
			}
			VoteItem item = new VoteItem();
			item.setGroupId(groupId);
			item.setKey(key);
			item.setNote(note);;
			voteDao.insertVoteItem(item);
			Set<Integer> set = vote.get(item.getKey());
			if (set == null){
				set = new HashSet<Integer>();
				vote.put(item.getKey(), set);
			}
		}
		this.voteFlag = true;
		return groupId;
	}
	
	//停止投票
	public Integer stopVote(){
		VoteGroup group = this.voteDao.selectLastVoteGroup();
		if (group == null){
			return -1;
		}
		this.voteFlag = false;
		List<VoteItem> items = this.voteDao.selectVoteItemByGroup(group.getId());
		for (VoteItem voteItem : items) {
			Set<Integer> set = vote.get(voteItem.getKey());
			voteItem.setCount(set.size());
			StringBuilder authIds = new StringBuilder();
			for (Integer authId : set) {
				authIds.append(authId).append(",");
			}
			voteItem.setAuthIds(authIds.toString());
			voteDao.updateVoteItem(voteItem);
		}
		this.vote = null;
		this.checkSet = null;
		group.setEndTime(new Date());
		group.setStatus(1);
		this.voteDao.updateVoteGroup(group);
		return group.getId();
	}
	
	
	//投票
	public void vote(String key,int authId){
		if (voteFlag){
			if (this.vote == null){
				return;
			}
			if (this.vote.containsKey(key)){
				boolean check = checkSet.add(authId);
				if (!check){
					return;
				}
				boolean add = this.vote.get(key).add(authId);
				if (add){
					log.info("vote success: key "+key+" auth "+authId);
				}
			}
		}
	}
	
	
	//获取历史投票信息
	public List<VoteGroup> getVoteGroupList(){
		return this.voteDao.selectVoteGroupAll();
	}
	
	//获取投票信息
	public VoteGroup getVoteGroup(Integer groupId){
		VoteGroup group = null;
		if (groupId == null){
			group = this.voteDao.selectLastVoteGroup();
		} else {
			group = this.voteDao.selectVoteGroupById(groupId);
		}
		if (group == null){
			return null;
		}
		List<VoteItem> items = this.voteDao.selectVoteItemByGroup(group.getId());
		for (VoteItem voteItem : items) {
			if (group.getStatus() == 0){
				voteItem.setCount(this.vote.get(voteItem.getKey()).size());
			}
			group.setTotal(voteItem.getCount()+group.getTotal());
		}
		group.setItems(items);
		return group;
	}
	
	//根据itemId获取详情
	public VoteItem getVoteItem(Integer id){
		VoteItem item = this.voteDao.selectVoteItemById(id);
		if (item == null){
			return null;
		}
		List<Auth> auths = new ArrayList<Auth>();
		Set<Integer> authIds = strToSet(item.getAuthIds());
		for (Integer authId : authIds) {
			Auth auth = authService.getCacheAuth(authId);
			if (auth != null){
				auths.add(auth);
			}
		}
		item.setAuths(auths);
		return item;
	}
	
	private Set<Integer> strToSet(String authIds){
		Set<Integer> set = new HashSet<Integer>();
		String[] split = authIds.split(",");
		for (int i = 0; i < split.length; i++) {
			String authId = split[i];
			if (StringUtils.isNotBlank(authId)){
				try {
					set.add(Integer.valueOf(authId));
				} catch (NumberFormatException e) {
				}
			}
		}
		return set;
	}
	
	
}
